package com.tiance.domainservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.tiance.dal.dao.IntegrationHistoryDAO;
import com.tiance.dal.dao.IntegrationRuleDAO;
import com.tiance.dal.dao.MemberDAO;
import com.tiance.dal.dataobject.IntegrationHistoryDO;
import com.tiance.dal.dataobject.IntegrationRuleDO;
import com.tiance.dal.dataobject.MemberDO;
import com.tiance.domainservice.assemble.DOAssemble;
import com.tiance.domainservice.domain.IntegrationDomain;
import com.tiance.domainservice.service.IntegrationService;
import com.tiance.domainservice.utils.MemberUtil;
import com.tiance.enums.IntegrationTypeEnum;
import com.tiance.exception.BusinessException;
import com.tiance.integration.cache.MapCacheUtil;
import com.tiance.utils.DataUtil;
import com.tiance.utils.MapUtil;
import com.tiance.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2019/2/14
 *
 * Description：
 *
 * Modification History:
 *
 */
@Service
public class IntegrationServiceImpl implements IntegrationService {

    /** logger */
    protected static final Logger logger = LoggerFactory.getLogger(IntegrationServiceImpl.class);

    @Resource
    private IntegrationHistoryDAO integrationHistoryDAO;
    @Resource
    private IntegrationRuleDAO    integrationRuleDAO;
    @Resource
    private MemberDAO             memberDAO;
    @Override
    public List<IntegrationHistoryDO>  queryIntegrationHistory(IntegrationDomain integrationDomain) {
        Map<String,Object> map= MapUtil.params2Map(new Object[]{ "memberId", integrationDomain.getMemberId()},
                new Object[]{ "openid", StringUtil.trimNull(integrationDomain.getOpenid())},
                new Object[]{"integrationType",StringUtil.trimNull(integrationDomain.getIntegrationType())});

        logger.info("开始查询积分/信用数据，参数:{}", JSON.toJSONString(map));
        List<IntegrationHistoryDO> integrationHistoryDOList=integrationHistoryDAO.queryIntegrationHistory(map);
        logger.info("结束查询积分信用数据，返回数据:{}", JSON.toJSONString(integrationHistoryDOList));

        return integrationHistoryDOList;
    }

    @Override
    public void addIntegration(boolean getLock,IntegrationDomain integrationDomain) {
        //1查询积分规则
        Map<String,Object> ruleParammap= MapUtil.params2Map(new Object[]{ "ruleCode",integrationDomain.getIntegrationRuleCode().getCode()},
                new Object[]{ "belongType", integrationDomain.getBelongType()});

        logger.info("开始查询积分/信用规则，参数:{}", integrationDomain.getIntegrationRuleCode());
        IntegrationRuleDO integrationRuleDO=integrationRuleDAO.queryRuleByIntegrationRuleCode(ruleParammap);
        logger.info("结束查询积分/信用规则，返回数据:{}", JSON.toJSONString(integrationRuleDO));

        if(null==integrationRuleDO){
            throw new BusinessException("未知的积分规则，请联系管理人员!");
        }
        Map<String,Object> map= MapUtil.params2Map(new Object[]{ "id", integrationDomain.getMemberId()});
        logger.info("开始查询会员信息，参数:{}", JSON.toJSONString(map));
        MemberDO  oldMemberDO=memberDAO.queryMember(map);
        logger.info("结束查询会员信息，返回数据:{}", JSON.toJSONString(oldMemberDO));
        if(null==oldMemberDO){
            throw new BusinessException("会员["+integrationDomain.getMemberId()+"]不存在!");
        }
        //2.调整会员积分/信用
        try {
            if (!(getLock||MapCacheUtil.lock(integrationDomain.getMemberId() + ""))) {
                throw new BusinessException("该会员正在被操作，请稍后再试!");
            }

            MemberDO newMemberDO= MemberUtil.changeIntegration(oldMemberDO,integrationDomain.getIntegrationType(),integrationRuleDO);
            logger.info("开始更新会员信息，参数:{}", JSON.toJSONString(newMemberDO));
            Long updateCount=memberDAO.updateMemberIntegralAndCredit(newMemberDO);
            logger.info("结束更新会员信息，更新条数:{}", updateCount);

        }finally {
            if(!getLock){
                MapCacheUtil.unlock(integrationDomain.getMemberId()+"");
            }
        }
        //3.插入积分历史记录

        IntegrationHistoryDO integrationHistoryDO=new IntegrationHistoryDO();
        integrationHistoryDO.setMemberId(oldMemberDO.getId());
        integrationHistoryDO.setOpenid(oldMemberDO.getOpenid());
        integrationHistoryDO.setIntegrationType(integrationDomain.getIntegrationType());
        integrationHistoryDO.setOperateType(integrationRuleDO.getOperateType());
        integrationHistoryDO.setIntegrationValue(integrationRuleDO.getIntegrationValue());
        logger.info("开始插入积分/信用历史记录，参数:{}", JSON.toJSONString(integrationHistoryDO));
        Long count=integrationHistoryDAO.insert(integrationHistoryDO);
        logger.info("结束插入积分/信用历史记录，是否插入成功:{}", count>0?true:false);
        if(count<1){
            throw new BusinessException("插入失败");
        }
    }
}
